<script setup lang="ts">
// 抽屉代码
import { defineProps, ref, withDefaults } from "vue";
import { aiGenerateQuestionUsingPost } from "@/api/questionController";
import message from "@arco-design/web-vue/es/message";

const visible = ref(false);

const handleClick = () => {
  visible.value = true;
};
const handleOk = () => {
  visible.value = false;
};
const handleCancel = () => {
  visible.value = false;
};

//数据导入
interface Props {
  id: string;
  onSuccess?: (result: API.QuestionContentDTO[]) => void;
  onSSESuccess?: (result: API.QuestionContentDTO) => void;
  onSSEStart?: (event: any) => void;
  onSSEClose?: (event: any) => void;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => {
    return "";
  },
});

const from = ref<API.AiGenerateQuestionRequest>({
  id: Number(props.appId),
  questionNumber: 10,
  optionNumber: 2,
});

let submitting = ref(false);

/**
 * 提交
 */
const handleSubmit = async () => {
  if (!props.appId || !from.value) {
    return;
  }
  submitting.value = true;
  let res = await aiGenerateQuestionUsingPost({
    id: props.appId as any,
    questionNumber: from.value.questionNumber,
    optionNumber: from.value.optionNumber,
  });
  if (res.data.code === 0) {
    if (props.onSuccess) {
      props.onSuccess(res.data.data);
    } else {
      message.success("Ai题目生成成功");
    }
    handleCancel();
  } else {
    message.error("生成失败：" + res.data.message);
  }
  submitting.value = false;
};

let sseSubmitting = ref<boolean>(false);

//SSE生成题目
const doSSESubmit = () => {
  if (!props.appId) {
    return;
  }
  sseSubmitting.value = true;
  // 创建 SSE 请求
  const eventSource = new EventSource(
    // todo 手动填写完整的后端地址
    "http://localhost:8101/api/question/ai_generate/sse" +
      `?appId=${props.appId}&optionNumber=${from.value.optionNumber}&questionNumber=${from.value.questionNumber}`
  );
  let first = true;
  // 接收消息
  eventSource.onmessage = function (event) {
    if (first) {
      props.onSSEStart?.(event);
      handleCancel();
      first = !first;
    }
    props.onSSESuccess?.(JSON.parse(event.data));
  };
  // 报错或连接关闭时触发
  eventSource.onerror = function (event) {
    if (event.eventPhase === EventSource.CLOSED) {
      console.log("关闭连接");
      props.onSSEClose?.(event);
      eventSource.close();
    } else {
      eventSource.close();
    }
  };
  sseSubmitting.value = false;
};
</script>

<template>
  <div id="aiGenerateDrawer">
    <a-button type="outline" @click="handleClick">Ai生成题目</a-button>
    <a-drawer
      :width="340"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      unmountOnClose
    >
      <template #title> AI生成题目</template>
      <div>
        <a-form
          :model="from"
          label-align="left"
          auto-label-width
          @submit="handleSubmit"
        >
          <a-form-item label="应用 id">
            {{ id }}
          </a-form-item>
          <a-form-item label="题目数量">
            <a-input-number
              v-model="from.questionNumber"
              placeholder="请输入题目数"
            />
          </a-form-item>
          <a-form-item label="选项数量">
            <a-input-number
              v-model="from.optionNumber"
              placeholder="请输入选项数"
            />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button
                :loading="submitting"
                type="primary"
                size="medium"
                @click="handleSubmit"
              >
                {{ submitting ? "生成中" : "一键生成" }}
              </a-button>
              <a-button
                :loading="sseSubmitting"
                type="outline"
                size="medium"
                @click="doSSESubmit"
              >
                {{ submitting ? "生成中" : "实时生成" }}
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </div>
</template>

<style scoped></style>
